<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\EthAccount;
use app\common\model\EthAccountLog;
use app\common\model\Member;
use app\common\model\OtcCancelLog;
use app\common\model\OtcCustomer;
use app\common\model\OtcOrder;
use app\common\model\OtcShop;
use app\common\model\SbNotice;
use app\common\model\ShopAccountLog;
use app\common\model\ShoPoundagLog;
use app\common\model\ShopPoundageLog;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserPayType;
use app\common\model\UserSms;
use app\common\model\Wallet;
use think\Db;

/**
 * 用户接口逻辑
 */
class C2c extends ApiBase
{


    /***
     * otc交易列表
     */

    public function oct_trade_list($data){
        $where['surplus_number']=['gt',0];
        $where['wallet_id']=$data['wallet_id'];
        $where['type']=2;
        $where['status']=1;
        $where['state']=0;
        $where['is_recommend']=1;
        $list=$this->modelOtcTrading->getList($where,'id,surplus_number,user_id,price,min_money,total,shop_id,is_alipay,is_weixin,is_bank,wallet_id','price asc ,id desc');
        foreach ($list as $k=>$v){
            $list[$k]['trade_count']=$v->shop->total_count;
            $list[$k]['wallet_name']=$v->wallet->data['name'];
            $list[$k]['volume']=$v->shop->completion_rate;
            $list[$k]['username']=$v->shop->shop_name;
            unset($v->shop);
            unset($v->wallet);
        }
        return $list;
    }


    /***
     * 撤回店铺买单
     */

    public function trade_withdraw($data){
        Db::startTrans();
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelOtcTrading->where(['id'=>$data['id'],'user_id'=>$uid])->lock(true)->find();

        if($info){
            if($info['state']!=1 && $info['state']!=0){
                return ajaxreturn(1,lang('交易状态错误'));
            }
//            $count=$this->modelOtcOrder->where(['otc_id'=>$data['id'],'state'=>['in',[1,3,6]]])->count();
//            if($count>0){
//                return ajaxreturn(1,lang('有订单未完成,不能撤回'));
//            }
            $cance_number=$this->modelOtcTrading->where(['shop_id'=>$info['shop_id'],'is_auto'=>0,'user_id'=>$uid,'state'=>3,'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->count();
            $cancel_count=getConfig('otc_shop_cancel_count');
            if($cance_number>=$cancel_count){
                return ajaxreturn(1,lang('当天取消次数已达到上限'));
            }

            try{

                $this->modelOtcTrading->where(['id'=>$data['id']])->update(['state'=>3]);
                $shop=$this->modelOtcShop->where(['id'=>$info['shop_id']])->lock(true)->find();
                if($info['type']==2){

                    $shop->cancel_number+=$info['surplus_number'];
                    $shop->number_lock-=$info['surplus_number'];
                    ShopAccountLog::create([
                        'user_id'=>$member['id'],
                        'number'=>$info['number'],
                        'shop_id'=>$shop['id'],
                        'remark'=> '撤回出售订单退回',
                        'is_add'=>1,
                        'type'=>2
                    ]);

                }
                $cance_number+=1;
                if($cance_number>=$cancel_count){
                    OtcCancelLog::create([
                        'username'=>$member['username'],
                        'mobile'=>$member['mobile'],
                        'area'=>$member['area'],
                        'number'=>1,
                        'type'=>2,
                        'remark'=>'OTC限制店铺发布(每日)',
                        'shop_id'=>$shop['id'],
                        'user_id'=>$member['id']
                    ]);
                    if($shop['penalty_time']>time()){
                        $shop['penalty_time']+=86400;
                    }else{
                        $shop['penalty_time']=time()+86400;
                    }
                    $shop->is_release=0;

                }
                $shop->save();
                if($info['type']==1){
                    user_notice($member['id'],'您的代发订单取消成功,取消次数'.$cance_number.'次');

                }else{
                    user_notice($member['id'],'您的出售订单已发布成功,取消次数'.$cance_number.'次');

                }
                Db::commit();

                return ajaxreturn(0,lang('发布订单取消成功，取消次数'.$cance_number.'次'));
            }catch (\Exception $e){

                Db::rollback();
                return ajaxreturn(1,$e->getMessage());
            }
        }else{
            return ajaxreturn(1,lang('交易不存在'));
        }
    }


    /***
     * 一键买币
     */

    public function onekey_otc($data){
        $wallet=Wallet::get($data['wallet_id']);
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $start_time=$this->logicApiBase->member['start_time'];
        $end_time=$this->logicApiBase->member['end_time'];
        if(TIME_NOW > strtotime(date('Y-m-d '.$end_time))  || TIME_NOW < strtotime(date('Y-m-d '.$start_time))){
            return ajaxreturn(1,lang('非常抱歉的通知您，当前时间未能找到在线的商家为您提供购买充值服务，可交易充值的实际时间为，'.$start_time.'时间-'.$end_time.'时间内'));
        }


        if($data['type']==1){
            $buy_money=$data['money']*$wallet['parities'];

        }else{
            $buy_money=$data['money'];
        }
        $min_money=getConfig('otc_min_money');
        $max_money=getConfig('otc_max_money');
        $money_price=getPrice();
        if(!in_array($buy_money,$money_price)){
            if($data['type']==1){
                return ajaxreturn(1,lang('您输入的购买数量价值不在200起和200的倍数内，不在法币购买的交易范围内'));
            }else{
                return ajaxreturn(1,lang('由于您输入的金额不再法币购买的范围内，您可以尝试如：300~600~900等金额'));
            }


        }
        if( $buy_money< $min_money){
            if($data['type']==1){

                 return ajaxreturn(1,lang('您输入的购买数量已低于最小交易的限制为价值￥'.$min_money.'的购买数量'));
            }else{
                return ajaxreturn(1,lang('金额不得低于最低金额'.' '.$min_money));
            }



        }
        if( $buy_money> $max_money ){
            if($data['type']==1){

                return ajaxreturn(1,lang('您输入的购买数量已超过最大交易的限制为价值￥'.$max_money.'的购买数量'));
            }else{
                return ajaxreturn(1,lang('金额不得高于最大金额'.' '.$max_money));
            }

        }
        $ids1=Member::where(['path'=>['like','%,'.$member['id'].',%']])->column('id');
        $ids2=explode(',',rtrim($member['path'], ","));
        $ids=array_merge($ids1,$ids2);
        $where['a.wallet_id']=$data['wallet_id'];
        $where['a.type']=2;
        $where['a.user_id']=['neq',$uid];
//        $where['a.user_id']=['not in',$ids];
        $where['a.state']=['in',[1,0]];
        $where['s.status']=1;
        $where['a.surplus_total']=$buy_money;
        $where['c.is_black']=0;
        $where['a.status']=1;
        $where['s.is_match']=1;
        $where['s.shop_switch']=1;
        $where['c.start_time_int']=['neq',0];
        $where['c.start_time_int']=['lt',TIME_NOW];
        $where['c.end_time_int']=['neq',0];
        $where['c.end_time_int']=['gt',TIME_NOW];
        $list=$this->modelOtcTrading->alias('a')->field('a.id,a.surplus_number,is_auto,a.user_id,a.price,a.min_money,a.max_money,a.shop_id,a.is_alipay,a.is_weixin,a.is_bank,a.wallet_id')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order('feed_count desc ,match_count asc ,price asc ,a.id asc')->find();
        if(!$list){
            unset( $where['a.user_id']);
            $where['c.is_company']=1;
            $where['a.user_id']=['neq',$uid];
            $list=$this->modelOtcTrading->alias('a')->field('a.id,a.surplus_number,is_auto,a.user_id,a.price,a.min_money,a.max_money,a.shop_id,a.is_alipay,a.is_weixin,a.is_bank,a.wallet_id')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order('feed_count desc ,match_count asc ,price asc ,a.id asc')->find();
        }

        if(!$list){
            $number=$buy_money/$wallet['parities'];
            $where1['a.wallet_id']=$data['wallet_id'];
            $where1['a.user_id']=['not in',$ids];
            $where1['c.is_black']=0;
            $where1['a.is_match']=1;
            $where1['a.is_release']=1;
            $where1['a.state']=2;
            $where1['a.status']=1;
            $where1['a.number_do']=['>=',$number];
            $where1['a.shop_switch']=1;
            $where1['c.single_amount']=$buy_money;
            $where1['c.start_time_int']=['neq',0];
            $where1['c.start_time_int']=['lt',TIME_NOW];
            $where1['c.end_time_int']=['neq',0];
            $where1['c.end_time_int']=['gt',TIME_NOW];
            $shop_info=$this->modelOtcShop->alias('a')->field('a.*')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where1)->order('c.atuo_count asc,a.id desc')->find();

            if(!$shop_info){
                unset( $where1['a.user_id']);
                $where1['c.is_company']=1;
                $where1['a.user_id']=['neq',$uid];
                $shop_info=$this->modelOtcShop->alias('a')->field('a.*')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where1)->order('c.atuo_count asc,a.id desc')->find();

                if(!$shop_info){
                    unset( $where1['c.single_amount']);
                    unset( $where1['c.is_company']);
                    //智能化
                    $where1['c.is_intellect']=1;
                    $shop_info=$this->modelOtcShop->alias('a')->field('a.*')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where1)->order('c.atuo_count asc,a.id desc')->find();
                }
            }

            if($shop_info){
                //创建出售订单
                $ali_pay=UserPayType::where(['user_id'=>$shop_info['user_id'],'type'=>1,'status'=>1,'is_use'=>1])->count();
                $weichat_pay=UserPayType::where(['user_id'=>$shop_info['user_id'],'type'=>2,'status'=>1,'is_use'=>1])->count();
                $bank_pay=UserPayType::where(['user_id'=>$shop_info['user_id'],'type'=>3,'status'=>1,'is_use'=>1])->count();
                if($ali_pay+$weichat_pay+$bank_pay==0){
                    return [];
                }

                //生成订单
                $res=$this->modelOtcTrading->setInfo([
                    'type'=>2,
                    'shop_id'=>$shop_info['id'],
                    'number'=>$number,
                    'wallet_id'=>$shop_info['wallet_id'],
                    'price'=>$wallet['parities'],
                    'surplus_number'=>$number,
                    'total'=>$buy_money,
                    'surplus_total'=>$buy_money,
                    'remark'=>'店铺自动化生成',
                    'user_id'=>$shop_info['user_id'],
                    'is_alipay'=>$ali_pay>0?1:0,
                    'is_weixin'=>$weichat_pay>0?1:0,
                    'is_bank'=>$bank_pay>0?1:0,
                    'is_auto'=>1

                ]);
                if($number>$shop_info->cancel_number){
                    $second_number=$number-$shop_info->cancel_number;
                    $shop_info->cancel_number=0;
                    $shop_info->number_do-=$second_number;
                }else{
                    $shop_info->cancel_number-=$number;
                }
                $shop_info->member->atuo_count+=1;
                $shop_info->member->save();
                $shop_info->number_lock+=$number;
                $shop_info->save();
                $list=$this->modelOtcTrading->alias('a')->field('a.id,a.surplus_number,is_auto,a.user_id,a.price,a.min_money,a.max_money,a.shop_id,a.is_alipay,a.is_weixin,a.is_bank,a.wallet_id')->where(['id'=>$res])->find();


            }
        }
        if($list){
            if($data['type']==1){

                $buy_money=$data['money']*$list['price'];
                $buy_number=$data['money'];
            }else{
                $buy_money=$data['money'];
                $buy_number=$data['money']/$list['price'];
            }
            $list['buy_money']=$buy_money;
            $list['buy_number']=$buy_number;
            $list['trade_count']=$list->shop->total_count;
            $list['wallet_name']=$list->wallet->data['name'];
            $list['volume']=$list->shop->completion_rate;
            $list['username']=$list->shop->shop_name;
            unset($list->shop);
            unset($list->wallet);
        }

        return $list;
    }


//    /***
//     * 商家管理列表
//     */
//
//    public function my_trade_list(){
//        $member=$this->logicApiBase->member;
//        $uid=$member['id'];
//        $list=$this->modelOtcTrading->getList(['user_id'=>$uid],'id,surplus_number,number,type,user_id,price,min_money,max_money,is_alipay,is_weixin,is_bank,wallet_id,state','price asc ,id desc');
//        foreach ($list as $k=>$v){
//
//            $list[$k]['wallet_name']=$v->wallet->data['name'];
//            unset($v->wallet);
//            unset($v->shop);
//        }
//        return $list;
//    }








    /**
     * 下单
     */
    public function add_otc_order($data = [])
    {
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $start_time=strtotime(date('Y-m-d ').getConfig('otc_start_time'));
        if(TIME_NOW<$start_time){
            return ajaxreturn(1,lang('为了更加友好的服务玩家，商家开通的交易购买时间为').getConfig('otc_start_time').'-'.getConfig('otc_end_time'));
        }
        $end_time=strtotime(date('Y-m-d ').getConfig('otc_end_time'));
        if(TIME_NOW>$end_time){
            return ajaxreturn(1,lang('为了更加友好的服务玩家，商家开通的交易购买时间为').getConfig('otc_start_time').'-'.getConfig('otc_end_time'));
        }
        if($member['is_otc']==0 ){
            return ajaxreturn(1,lang('由于您多次发起充值，但未能完成付款，限冻结您的充值功能，解冻为1天时间，请知悉法币交易规则'));
        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number'])){
            return ajaxreturn(1,lang('格式不正确'));
        }

        $cancel_count=$this->modelOtcOrder->where(['user_id'=>$uid,'state'=>1])->count();
        if($cancel_count>=getConfig('otc_buy_max')){
            return ajaxreturn(1,lang('买家每次发起交易最大不能超过'.getConfig('otc_buy_max').'笔未付款订单'));
        }
        $time=time()+getConfig('otc_last_time')*60;
        Db::startTrans();
        try{
            $info=$this->modelOtcTrading->where(['id'=>$data['id']])->lock(true)->find();
            if($info['user_id']==$uid){
                return ajaxreturn(1,lang('不能接自己的单'));
            }

            if( $info['state']==2){
                return ajaxreturn(1,lang('广告方发生变化,停止下单'));
            }
            $arr=[
                'price'=>$info['price'],
                'wallet_id'=>$info['wallet_id'],
                'pay_expire_time'=>$time,
                'otc_type'=>$info['type'],
                'shop_id'=>$info['shop_id'],
                'otc_id'=>$info['id'],
            ];
            if($info['type']==1){
                $arr['user_id']=$info['user_id'];
                $arr['uid']=$uid;

            }else{
                $arr['uid']=$info['user_id'];
                $arr['user_id']=$uid;
            }

            if($data['type']==1){
                //按数量
                $arr['total']=$info['price']*$data['number'];
                $arr['number']=$data['number'];

            }else{
                //按金额

                $arr['total']=$data['number'];
                $arr['number']=$data['number']/$info['price'];
                if($data['number']==$info['max_money']){
                    $arr['number']=$info['surplus_number'];
                }
            }
            $pays=$payids=[];
            $ali_pay=UserPayType::where(['user_id'=>$info['user_id'],'type'=>1,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
            $count=0;
            if($ali_pay){
                if(count($ali_pay)>1){
                    foreach ($ali_pay as $k=>$v){
                        $money=OtcOrder::where(['uid'=>$info['user_id'],'pay_type'=>1,'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$v['id'].',%'],'create_time'=>['between',[getTodayStart(),getTodayEnd()]] ])->sum('total')+0;
                        if($money>$v['max_money']){
                            continue;
                        }else{
                            $v['image']= $v['image'];
                            $payids[]=$v['id'];
                            $pays[]=$v;
                            $count++;
                            break;

                        }
                    }
                }else{
                    $money=OtcOrder::where(['uid'=>$info['user_id'],'pay_type'=>1,'state'=>['not in',[4,5,13]],'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$ali_pay[0]['id'].',%']])->sum('total')+0;
                    if($money<$ali_pay[0]['max_money']){

                        $payids[]=$ali_pay[0]['id'];
                        $ali_pay[0]['image']=$ali_pay[0]->image;
                        $pays[]=$ali_pay[0];
                        $count++;
                    }

                }



            }
            $wechat_pay=UserPayType::where(['user_id'=>$info['user_id'],'type'=>2,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
            if($wechat_pay){
                if(count($wechat_pay)>1){
                    foreach ($wechat_pay as $k=>$v){
                        $money=OtcOrder::where(['uid'=>$info['user_id'],'pay_type'=>2,'state'=>['not in',[4,5,13]],'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$v['id'].',%']])->sum('total')+0;
                        if($money>$v['max_money']){
                            continue;
                        }else{
                            $payids[]=$v['id'];
                            $v['image']= $v['image'];
                            $pays[]=$v;
                            $count++;
                            break;

                        }
                    }
                }else{
                    $money=OtcOrder::where(['uid'=>$info['user_id'],'pay_type'=>2,'state'=>['not in',[4,5,13]],'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$wechat_pay[0]['id'].',%']])->sum('total')+0;
                    if($money<$wechat_pay[0]['max_money']){

                        $payids[]=$wechat_pay[0]['id'];
                        $wechat_pay[0]['image']=$wechat_pay[0]->image;
                        $pays[]=$wechat_pay[0];
                        $count++;
                    }

                }

            }

            $bank_pay=UserPayType::where(['user_id'=>$info['user_id'],'type'=>3,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
            if($bank_pay){

                if(count($bank_pay)>1){
                    foreach ($bank_pay as $k=>$v){
                        $money=OtcOrder::where(['uid'=>$info['user_id'],'pay_type'=>3,'state'=>['not in',[4,5,13]],'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$v['id'].',%']])->sum('total')+0;
                        if($money>$v['max_money']){
                            continue;
                        }else{
                            $payids[]=$v['id'];
                            $pays[]=$v;
                            $count++;
                            break;

                        }
                    }
                }else{
                    $money=OtcOrder::where(['uid'=>$info['user_id'],'pay_type'=>3,'state'=>['not in',[4,5,13]],'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$bank_pay[0]['id'].',%']])->sum('total')+0;
                    if($money<$bank_pay[0]['max_money']){
                        $payids[]=$bank_pay[0]['id'];
                        $pays[]=$bank_pay[0];
                        $count++;
                    }

                }
            }
            if(!$pays){
                return ajaxreturn(1,lang('该商家每日收款已达到上限'));
            }
            if($count==0){
                //禁止匹配
                $shop=OtcShop::get(['id'=>$info['shop_id']]);
                if($shop['no_match_time']>time()){
                    $shop['no_match_time']+=86400;
                }else{
                    $shop['no_match_time']=86400;
                }
                $shop->is_match=0;
                $shop->save();
                OtcCancelLog::create([
                    'username'=>$member['username'],
                    'mobile'=>$member['mobile'],
                    'area'=>$member['area'],
                    'number'=>1,
                    'type'=>3,
                                                                                                                                                                                                                                                                                                                                                                                                                                'shop_id'=>$shop['id'],
                    'remark'=>'OTC限制店铺匹配(收款金额超过每日限制)',
                    'user_id'=>$member['id']
                ]);
            }
            if($payids){
                UserPayType::where(['id'=>['in',$payids]])->setInc('use_count',1);
            }
            $arr['pay_ids']=','.implode(',',$payids).',';
            $arr['pay_json']=json_encode($pays);
            $arr['total']=$info['surplus_total'];
            $arr['number']=$info['surplus_number'];
            $money_price=getPrice();
            if(!in_array($arr['total'],$money_price)){
                return ajaxreturn(1,lang('由于您输入的金额不再法币购买的范围内，您可以尝试如：300~600~900等金额'));
            }
            $arr['channel']='CCIE';
            $min_money=getConfig('otc_min_money');
            $max_money=getConfig('otc_max_money');
            if( $arr['total']< $min_money){
                return ajaxreturn(1,lang('金额不得低于最低金额'.' '.$min_money));
            }
            if( $arr['total']> $max_money ){
                return ajaxreturn(1,lang('金额不得高于最大金额'.' '.$max_money));
            }
            $info->match_count+=1;
            $info->state=1;
            $info->surplus_number=0;
            $info->surplus_total-=$arr['total'];
            $info->save();
            $info->shop->total_count+=1;
            $info->shop->save();
            if($info['type']==1){
                $poundage=getConfig('otc_receive_poundage')/100;
            }else{
                $poundage= getConfig('otc_collection_poundage')/100;
            }
            $arr['poundage_number']=$arr['number']*$poundage;
            $result=$this->modelOtcOrder->setInfo($arr);
            user_notice($uid,'尊敬的会员您好，你发起了一笔法币交易的订单，请尽快完成付款，如因超时付款系统会自动封闭限制您的账户登录，请珍惜您的信用点滴，感谢您的支持和理解');

            //发送短信
            // $lang = in_array($member['area'], ['86', '852', '853', '886']) ? 'zh-hk' : 'en-us';
            // $content=getConfig('otc_match_shop_'.$lang);
            // $shop_member = Db::name("member")->where(["id"=>$shop['user_id']])->find();
            // $data = [
            //     'mobile' => $shop_member['mobile'],
            //     'content' => $content,
            //     'create_time' => TIME_NOW,
            //     'sms_type' => 2,
            //     'type' => 0,
            //     'area' => $shop_member['area']
            // ];
            // $sms = UserSms::create($data);

            // if (getConfig('sms_is_test') != 1) {
            //     $state = send_sms($shop_member['mobile'], $content, config('settings'), $shop_member['area']);
            //     if ($state) {
            //         UserSms::where(['id' => $sms->id])->update(['state' => 2]);
            //     }  
                
            // }
            Db::commit();
            return  ['id'=>$result,'msg'=>lang('您的法币购买需求，已为您匹配商家成功，请及时付款，防止产生不良记录和被封号')];
        }catch (\Exception $e){
            Db::rollback();
              return  ajaxreturn(1,$e->getMessage());
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }




    }

    /**
     * 订单详情
     */

    public function otc_order_info_pay($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelOtcOrder->getInfo(['id'=>$data['id']]);
        if($info['user_id'] !=$uid &&  $info['uid'] !=$uid ){
            return  ajaxreturn(1,lang('参数错误'));
        }


        $info['expire_time1']=$info['expire_time']-time();
        $arr=[];
        if($info->trade->is_alipay==1){
            $alipay=$this->modelUserPayType->getInfo(['type'=>1,'user_id'=>$info['uid'],'status'=>1]);
            $arr['alipay']=$alipay;
        }
        if($info->trade->is_weixin==1){
            $weixin=$this->modelUserPayType->getInfo(['type'=>2,'user_id'=>$info['uid'],'status'=>1]);
            $arr['weixin']=$weixin;
        }
        if($info->trade->is_bank==1){
            $bank=$this->modelUserPayType->getInfo(['type'=>3,'user_id'=>$info['uid'],'status'=>1]);
            $arr['bank']=$bank;
        }

        unset($info->trade);
        $info['paylist']=$arr;

        return $info;
    }


    /**
     * 订单详情
     */

    public function otc_order_info($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelOtcOrder->getInfo(['id'=>$data['id']]);
//        if($info['user_id'] !=$uid &&  $info['uid'] !=$uid ){
//            return  ajaxreturn(1,lang('参数错误'));
//        }

        $info['wallet_name']=$info->wallet->data['name'];
        $info['wallet_logo']=$info->wallet->image;
        $info['member_name']=$info->member->username;
        $info['user_name']=$info->user->username;
        $info['buy_phone']=$info->member->mobile;
        $info['buy_area']=$info->member->area;
        $info['image']=$info->image;
        $info['notice_count']=OtcCustomer::where(['otc_order_id'=>$data['id'],'is_read'=>0,'user_id'=>$member['id']])->count();
        $info['sell_phone']=$info->user->mobile;
        $info['sell_area']=$info->user->area;
        $info['shop_name']=Db::name("otc_shop")->where(["id"=>$info['shop_id']])->find()['shop_name'];
        $info['expire_time1']=$info->getData('pay_expire_time')-time();
        $info['expire_time2']=$info->getData('receive_expire_time')-time();
        if($info['otc_type']==1){
            $info['paylist']=$info->transfer->userpay;
        }else{
            if($info->userpay){
                $info['paylist']=$info->userpay;
            }else{
//                if($info->trade->is_alipay==1){
//                    $alipay=$this->modelUserPayType->getInfo(['type'=>1,'user_id'=>$info['uid'],'status'=>1]);
//                    if($alipay){
//                        $alipay['image']= $alipay['image'];
//                        $arr[]=$alipay;
//                    }
//
//                }
//                if($info->trade->is_weixin==1){
//                    $weixin=$this->modelUserPayType->getInfo(['type'=>2,'user_id'=>$info['uid'],'status'=>1]);
//                    if($weixin){
//                        $weixin['image']= $weixin['image'];
//                        $arr[]=$weixin;
//                    }
//
//
//                }
//                if($info->trade->is_bank==1){
//                    $bank=$this->modelUserPayType->getInfo(['type'=>3,'user_id'=>$info['uid'],'status'=>1]);
//                    if($bank) {
//                        $arr[]=$bank;
//                    }
//
//                }
                $info['paylist']=[];
            }
        }




        if($info->feedback){
            $feedback['content']=$info->feedback['content'];
            $feedback['buy_days']=$info->feedback['buy_days'];
            $feedback['state']=$info->feedback['state'];
            $feedback['shop_days']=$info->feedback['shop_days'];
            $feedback['no_match_days']=$info->feedback['no_match_days'];
            $feedback['punish']=$info->feedback['punish'];
            $feedback['create_time']=$info->feedback['create_time'];
            $feedback['freeze']=$info->feedback['freeze'];
            $feedback['feedback_type']=$info['feedback_type'];
            $feedback['feedback_content']=$info['feedback_content'];
            $feedback['feedback_image']=$info->feedback->cover_id?get_picture_url($info->feedback->cover_id,false):'';
            unset($info->feedback);
        }else{
            $feedback=[];
        }
        $info['feed']=$feedback;
        // unset($info->trade);
        unset($info->member);
        unset($info->user);
        unset($info->wallet);
//        dd($info);
        return $info ;
    }



    /**
     * 改变订单状态
     */

    public  function update_otc_state($data){

        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelOtcOrder->getInfo(['id'=>$data['id']]);
        switch ($data['type']){
            case 1 :
                //确认付款
                $state=3;
                if($info['user_id'] !=$uid ){
                    return  ajaxreturn(1,lang('参数错误'));
                }
                if(!$data['cover_id'] ){
                    return  ajaxreturn(1,lang('参数错误'));
                }
                if(!$data['pay_type'] ){
                    return  ajaxreturn(1,lang('请选择支付方式'));
                }
                if($info['pay_expire_time']>TIME_NOW){
                    return  ajaxreturn(1,lang('订单已超时'));
                }



                break;
            case 2 :
                //取消订单

                $state=4;
                break;
            case 3:
                //放行订单
                if( $info['uid'] !=$uid ){
                    return  ajaxreturn(1,lang('参数错误'));
                }

                $state=2;
                break;
            default :
                return  ajaxreturn(1,lang('参数错误'));
                break;

        }
        Db::startTrans();
        try{
            if($state==4){

                if($info['state']!=1){
                    return  ajaxreturn(1,lang('订单已超时'));
                }
                //取消退回

                if($info['withdrwal_id']>0){

                    Db::name('transfer')->where(['id'=>$info['withdrwal_id']])->setInc('money',$info['total']);
                    //待匹配
                    Db::name('transfer')->where(['id'=>$info['withdrwal_id']])->update(['state'=>4]);
                }
                $cancel_info=OtcOrder::where(['user_id'=>$uid,'state'=>5,'pay_time'=>0,'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->count();
                $cancel_count=getConfig('otc_user_cancel_count');
                if($cancel_info>=$cancel_count){
                    return ajaxreturn(1,lang('当天取消次数已达到上限'));
                }
                $cancel_info+=1;
                if($cancel_info>=$cancel_count){

                    if($member['penalty_time']>time()){
                        $member['penalty_time']+=86400;
                    }else{
                        $member['penalty_time']=time()+86400;
                    }
                    $member->is_otc=0;
                    $member->save();
                    OtcCancelLog::create([
                        'username'=>$member['username'],
                        'mobile'=>$member['mobile'],
                        'area'=>$member['area'],
                        'number'=>1,
                        'type'=>1,
                        'remark'=>'OTC限制购买(每日)',
                        'user_id'=>$member['id']
                    ]);

                }
                Db::name('otc_trading')->where(['id'=>$info['otc_id']])->setInc('surplus_number',$info['number']);
                Db::name('otc_trading')->where(['id'=>$info['otc_id']])->setInc('surplus_total',$info['total']);
                Db::name('otc_trading')->where(['id'=>$info['otc_id']])->update(['state'=>0]);

            }

            if($state==2){
                //放行订单，交易成功
                if($info['state']!=3){
                    return  ajaxreturn(1,lang('订单已超时'));
                }
                if($info['receive_expire_time']>TIME_NOW){
                    return  ajaxreturn(1,lang('订单已超时'));
                }

                if(Db::name("otc_shop")->where(["id"=>$info["shop_id"]])->find()['poundage_type']==2){
                    $get_number=$info['number']-$info['poundage_number']*$info['price'];
                }else{
                    $get_number=$info['number'];
                }
                //发币

                if($info->member->mobile){
                    //发消息
                    $code=$info['serial_number'];
                    $code1=$info['number'];
                    $code2=$info->wallet->data['name'];
                    $lang=in_array($info->member->area,['86','852','853','886'])?'zh-hk':'en-us';
                    $content=getConfig('otc_success_notice_'.$lang);
                    $content=str_replace('{$code}', $code, $content);
                    $content=str_replace('{$code1}', $code1, $content);
                    $content=str_replace('{$code2}', $code2, $content);
                    $data = [
                        'mobile' => $info->member->mobile,
                        'content' => $content,
                        'create_time' => TIME_NOW,
                        'sms_type' => 2,
                        'type' => 0,
                        'area'=>$info->member->area
                    ];
                    $sms=UserSms::create($data);

                    if(getConfig('sms_is_test')!=1){
                        $res=send_sms($info->member->mobile,$content ,config('settings'),$info->member->area);
                        if($res){
                            UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                        }
                    }




                }


               

                if($info['otc_type']==1){

                    $withdrwal=Transfer::get($info['withdrwal_id']);
                    $info->shop->number_do+=$get_number;

                    ShopAccountLog::create([
                        'user_id'=>$info['user_id'],
                        'number'=>$get_number,
                        'shop_id'=>$info['shop_id'],
                        'remark'=> '购买代发金额',
                        'is_add'=>1,
                        'type'=>4
                    ]);

                    if($withdrwal['money']==0){
                        $count=OtcOrder::where(['state'=>['in',[1,3,6]] ,'withdrwal_id'=>$info['withdrwal_id']])->count();
                        if($count==1){
                            $withdrwal->state=1;
                            $withdrwal->save();
                        }
                    }
                    user_notice($info->user_id,'您的代发订单已确认，请查收');
                }else{
                    //
                    $user_account=UserAccount::where(['user_id'=>$info['user_id'],'wallet_id'=>1])->lock(true)->find();
                    $money=$get_number*$info['price'];
                    $user_account->balance+=$money;
                    $user_account->save();

                    //写入流水
                    UserAccountLog::create([
                        'user_id' => $info->user_id,
                        'number' => $money,
                        'wallet_id' =>1,
                        'before_blance' => $user_account->balance -$money,
                        'after_blance' => $user_account->balance,
                        'is_add' => 1,
                        'type' => 24,
                        'remark' =>'OTC买入',

                    ]);
                    //减去冻结
                    $info->shop->number_lock-=$info['number'];
                    if($info->trade->surplus_number==0){
                        $trade_count= Db::name('otc_order')->where(['otc_id'=>$info['otc_id'],'state'=>['in',[1,3,6,7,8]]])->count();
                        if($trade_count>=1){
                            //改变买卖单状态 已完成
                            $info->trade->state=2;
                            $info->trade->save();
                        }
                    }
                    if($info->trade->feed_count>0){
                        $info->trade->feed_count=0;
                        $info->trade->save();
                    }
                    user_notice($info->uid,'您的店铺usdt,有一笔订单金额'.$info['total'].'元，您已在'.date('Y-m-d H:i:s').'时间完成放行，由您在设备码为'.$member['uuid'].'上操作完成');
                    user_notice($info->user_id,'您的充值订单已确认，请查收');
                    //判断商家余额够不够，不够自动关闭店铺
                    $has_number=($info->shop->number_lock+$info->shop->number_do+$info->shop->cancel_number)*$info->wallet->parities;
                    if($has_number<300){
                        $info->shop->shop_switch=2;
                    }
                    $order_count=OtcOrder::where(['shop_id'=>$info['shop_id'],'otc_type'=>2,'state'=>3])->count();
                    if($order_count==0){
                        SbNotice::where(['user_id'=>$info['uid'],'type'=>3])->update(['is_read'=>1]);
                    }
                }


                $pay_time=$info->getData('pay_time')?$info->getData('pay_time'):TIME_NOW;
                $receive_minute=ceil((TIME_NOW-$pay_time)/60);
                SbNotice::create([
                    'type'=>2,
                    'shop_name'=>$info->shop->shop_name,
                    'number'=>$get_number,
                    'receive_minute'=>$receive_minute,
                    'order_id'=>$info['id'],
                    'user_id'=>$info['user_id'],
                    'wallet_id'=>$info['wallet_id']

                ]);
                $info->receive_minute=$receive_minute;
                //更新卖家成交量，发放手续费
                $info->shop->success_count+=1;
                if($info['poundage_number']){
                    $info->shop->poundage_number+=$info['poundage_number'];
                    ShopPoundageLog::create([
                        'user_id'=>$info->shop['user_id'],
                        'shop_id'=>$info['shop_id'],
                        'order_id'=>$info['id'],
                        'otc_id'=>$info['otc_id'],
                        'type'=>$info['withdrwal_id']>0?2:1,
                        'total'=>$info['poundage_number']*$info['price'],
                        'number'=>$info['poundage_number']
                    ]);
                }
                
                $info->shop->number_do+=$info['poundage_number'];
                $msg= $info->otc_type==1?'代发':'代收';
                ShopAccountLog::create([
                    'user_id'=>$info->shop['user_id'],
                    'number'=>$info['poundage_number'],
                    'shop_id'=>$info['shop_id'],
                    'remark'=>$msg. '手续费: 0.2%',
                    'is_add'=>1,
                    'type'=>3
                ]);
                $info->shop->turnover+=$info['total'];
                $info->shop->save();

            }


            //改变状态
            if($state==3){
                if($info['state']!=1){
                    return  ajaxreturn(1,lang('订单已超时'));
                }
                if(empty($data['cover_id'])){
                    return  ajaxreturn(1,lang('支付截图不能为空'));
                }
                if($info['otc_type']==1){
                    //商家已付款
                    Db::name('transfer')->where(['id'=>$info['withdrwal_id']])->update(['state'=>6]);
                    user_notice($info->uid,'您的总包提现申请由商家代发，商家已为给您的提现金额已打款成功，请您核对确认收款后，操作确认，如果商家已打款，您故意操作未收款，即被封号处理');
                }else{
                    $pay_json=json_decode($info['pay_json'],true);
                    $name='';
                    foreach ($pay_json as $k=>$v){
                        if($v['type']==$data['pay_type']){
                            $name=$v['bank_card'];
                        }
                    }
                    $time_now=date('Y-m-d H:i:s');
                    $msg='';
                    switch ($data['pay_type'] ){

                        case 1:

                            $msg='您的店铺USDT，由买家'.$info->member->username.'在'.$time_now.'时间完成了付款并上传了截图，收款账户为支付宝'.$name.'账户，请前往查收后尽快放行';
                            break;
                        case 2:
                            $msg='您的店铺USDT，由买家'.$info->member->username.'在'.$time_now.'时间完成了付款并上传了截图，收款账户为微信'.$name.'账户，请前往查收后尽快放行';
                            break;
                        case 3:
                            $msg='您的店铺USDT，由买家'.$info->member->username.'在'.$time_now.'时间完成了付款并上传了截图，收款账户为银行卡'.$name.'卡号，请前往查收后尽快放行';
                            break;

                    }
                    user_notice($info->uid,$msg);
                }

                $arr=[
                    'state'=>$state,
                    'cover_id'=>$data['cover_id'],
                    'pay_time'=>TIME_NOW,
                    'pay_type'=>$data['pay_type'],
                    'receive_expire_time'=>TIME_NOW+getConfig('otc_order_recieve_time')*60
                ];
                SbNotice::create([
                    'type'=>3,
                    'expire_time'=>$arr['receive_expire_time'],
                    'order_id'=>$info['id'],
                    'wallet_id'=>$info['wallet_id'],
                    'user_id'=>$info['uid'],
                    'otc_type'=>$info['withdrwal_id']>0?1:2,

                ]);
                Db::name('otc_order')->where(['id'=>$info['id']])->update($arr);
                if($info->user->mobile) {
                    $lang = in_array($info->member->area, ['86', '852', '853', '886']) ? 'zh-hk' : 'en-us';
                    $content = getConfig('otc_receive_notice_' . $lang);
                    $datas = [
                        'mobile' => $info->member->mobile,
                        'content' => $content,
                        'create_time' => TIME_NOW,
                        'sms_type' => 8,
                        'type' => 0,
                        'area' => $info->member->area
                    ];
                    $sms = UserSms::create($datas);

                    if (getConfig('sms_is_test') != 1) {
                        $res = send_sms($info->user->mobile, $content, config('settings'), $info->user->area);
                        if ($res) {
                            UserSms::where(['id' => $sms->id])->update(['state' => 2]);
                        }
                    }

                }

            }else{
                $arr=[
                    'state'=>$state,
                ];
                if($state==2){
                    $arr['receive_time']=TIME_NOW;
                    $arr['receive_minute']=$receive_minute;
                }

                Db::name('otc_order')->where(['id'=>$info['id']])->update($arr);
            }

            Db::commit();
            return  ajaxreturn(0,lang('成功'));
        }catch (\Exception $e){
            Db::rollback();
             return  ajaxreturn(1,$e->getMessage());
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

    }


    /***
     *订单反馈
     */

    public function  order_feedback($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelOtcOrder->getInfo(['id'=>$data['id']]);
        if($info['uid']!=$uid && $info['user_id']!=$uid ){
            return  ajaxreturn(1,lang('参数错误'));
        }
        if(empty($data['content'])){
            return ajaxreturn(1,lang('请输入申诉内容'));
        }
        if($info['state']!=3){
            return  ajaxreturn(1,lang('参数错误'));
        }
//        if(empty($data['contact'])){
//            return ajaxreturn(1,lang('请输入联系方式'));
//        }
        Db::startTrans();
        try{
            $feed=$this->modelOtcFeedback->getInfo(['order_id'=>$data['id']]);
            if(!$feed){
                $data['order_id']=$info['id'];
                $data['otc_id']=$info['otc_id'];
                $data['shop_id']=$info['shop_id'];
                $data['user_id']=$uid;
                unset($data['id']);
                $result= $this->modelOtcFeedback->setInfo($data);
            }else{
                $feed->state=1;
                $feed->content=$data['content'];
                !empty($data['cover_id'] ) && $feed->cover_id=$data['cover_id'];
                $feed->contact=$data['contact'];
                $feed->type_text='';
                $feed->credit=0 ;
                $feed->buy_days=0 ;
                $feed->shop_days=0 ;
                $feed->no_match_days=0 ;
                $feed->punish=0 ;
                $feed->real=0 ;
                $feed->freeze=0 ;
                $feed->save();
            }

            //改变状态
            Db::name('otc_order')->where(['id'=>$info['id']])->update(['state'=>6]);
            if($info['otc_type']==1){

                    //修改提现订单状态
                Db::name('transfer')->where(['id'=>$info['withdrwal_id']])->update(['state'=>9]);


                user_notice($info['user_id'],'您的代发订单被提现用户申诉');
                user_notice($info['uid'],'您的提现申诉订单提交成功，请耐心等待客户处理');
            }else{
                user_notice($info['user_id'],'您的购买申诉订单被店铺申诉');
                user_notice($info['uid'],'您的店铺USDT在'.$info->create_time.'时间，由买家'.$info->member->username.'购买的金额'.$info['total'].'元，并在'.$info['update_time'].'时间完成上传付款图片，因您进行操作投诉处理，客服进行介入调查，如情况属实进行处罚买家，如是您的过错，导致的投诉，系统会对您的店铺进行处罚');
            }

            Db::commit();
            return  ajaxreturn(0,lang('申诉成功,等待管理员处理'));
        }catch (\Exception $e){
            Db::rollback();
            return  ajaxreturn(1,$e->getMessage());
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

    }


    /***
     * 线下交易,钱包交易，提现列表
     */
    public function  order_list($data){
        if($this->logicApiBase->member['is_order_select']==0){
            return ajaxreturn(1,lang('网络状态异常'));
        }
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $where['user_id']=$uid;
        switch ($data['type']){
            case 1 :
                //线下交易
                $type=4;

                break;
            case 2 :
                //钱包交易

                $type=11;
                break;
            case 3:
                //提现
                $type=3;
                break;
            default :
                return  ajaxreturn(1,lang('参数错误'));
                break;

        }
        $where['type']=$type;

        $list=$this->modelTransfer->getList($where,'id,create_time,paytype,legal,form_wallet_id,number,state','id desc');
        switch ($data['type']){
            case 1 :
                //线下交易
                foreach ($list as $k =>$v){
                    if($v['paytype']==1){
                        $list[$k]['pay_name']=$v['legal']==1?lang('支付宝'):lang('微信');
                    }else{
                        $list[$k]['pay_name']=$v->wallet->data['name'];
                        unset($v->wallet);
                    }
                    $list[$k]['order_name']=lang('线下交易');
                }

                break;
            case 2 :
                //钱包交易

                foreach ($list as $k =>$v){
                    $list[$k]['order_name']=lang('钱包交易');
                    $list[$k]['pay_name']=$v->wallet->data['name'];
                    unset($v->wallet);
                }
                break;
            case 3:
                //提现
                foreach ($list as $k =>$v){

                    if($v->walletRechargeType->data['type']==4){
                        $list[$k]['pay_name']=$v->wallet->data['name'];
                        unset($v->wallet);

                    }else{

                        $list[$k]['pay_name']=$v->walletRechargeType->type_text;

                    }
                    unset($v->walletRechargeType);
                    $list[$k]['order_name']=lang('提现');
                }
                break;
            default :
                return  ajaxreturn(1,lang('参数错误'));
                break;

        }

        return $list;

    }



    /***
     * 线下交易,钱包交易，提现订单详情
     */

    public function order_detail($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelTransfer->getInfo(['id'=>$data['id'],'user_id'=>$uid],'id,state,create_time,form_wallet_id,paytype,legal,number,money,remark,serial_number,type');
        if(!$info){
            return  ajaxreturn(1,lang('参数错误'));
        }
        switch ($info['type']){
            case 4:
                if($info['paytype']==1){
                    $info['pay_name']=$info['legal']==1?lang('支付宝'):lang('微信');
                }else{
                    $info['pay_name']=$info->wallet->data['name'];
                    unset($info->wallet);
                }
                break;
            case 11:

                $info['pay_name']=$info->wallet->data['name'];
                unset($info->wallet);
                break;
            case 3:
                if($info['form_wallet_id']==0){
                    $info['pay_name']=$info->walletRechargeType->type_text;
                    unset($info->walletRechargeType);
                }else{
                    $info['pay_name']=$info->wallet->data['name'];
                    unset($info->wallet);
                }
                $info['arrival_time']=date('Y-m-d H:i:s',($info->data['create_time']+7200));
                break;
            default:
                return  ajaxreturn(1,lang('参数错误'));
                break;
        }
        $info['price']=  sprintf("%.6f",($info['money']/$info['number']));
        return $info;
    }


    /***
     * OTC交易订单列表
     */
    public function  otc_order_list($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];

        if(!empty($data['otc_id'])){
            $where['a.otc_id']=$data['otc_id'];

        }else{
//            $where['t.user_id']=['neq',$member['id']];

            $where['a.user_id']=$uid;
        }
        if(!empty($data['state'])){
            $where['a.state']=$data['state'];
        }
        if(!empty($data['is_handle'])){
            $where['a.state']=['in',[1,3]];
            unset($where['a.user_id']);
            $ids=OtcShop::where(['user_id'=>$uid,'state'=>2])->column('id');
            $where['a.shop_id']=['in',$ids];
        }
       // dd($where);
        $this->modelOtcOrder->alias('a');
        $join = [
            [SYS_DB_PREFIX . 'otc_trading t', 'a.otc_id = t.id'],
        ];
        $this->modelOtcOrder->join = $join;
        $list=$this->modelOtcOrder->getList($where,'a.otc_id,a.id,a.otc_type,a.uid,a.user_id,a.serial_number,a.wallet_id,a.create_time,a.number,a.state,a.pay_type','a.id desc');
        foreach ($list as $k =>$v){

            $list[$k]['pay_name']=$v->pay_text;
            $list[$k]['state_text']=$v->state_text;
            $wallet_name=$v->wallet->getData('name');
            $list[$k]['wallet_name']=$wallet_name;
            if($v['user_id']==$uid){
                $msg=lang('购买');
            }else{
                $msg=lang('出售');
            }
            $list[$k]['order_name']=$msg.$wallet_name;
            if($v['uid']==$uid){
                $list[$k]['is_add']=2;
            }else{
                $list[$k]['is_add']=1;
            }
            unset($v->wallet);
        }
        return $list;
    }


    /***
     * 店铺订单列表
     */

        public function  shop_order_list($data){

        $where=['shop_id'=>$data['id']];
        if(!empty($data['state'])){
            $where['state']=$data['state'];
        }

        $list=$this->modelOtcOrder->getList($where,'otc_id,id,otc_type,uid,user_id,serial_number,wallet_id,total,create_time,number,state,pay_type','id desc');
        foreach ($list as $k =>$v){

            $list[$k]['pay_name']=$v->pay_text;
            $list[$k]['state_text']=$v->state_text;
            $wallet_name=$v->wallet->getData('name');
            $list[$k]['wallet_name']=$wallet_name;
            $list[$k]['order_name']=$wallet_name;
            $list[$k]['total_money']=$v->wallet->parities*$v->total;
            unset($v->wallet);
        }

        return $list;

    }













}
